package com.a16.yuejian.yuejian.activity;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.a16.yuejian.yuejian.R;
import com.a16.yuejian.yuejian.adapter.SerachAdapter;
import com.a16.yuejian.yuejian.javabean.Serach;
import com.a16.yuejian.yuejian.listener.Listener;
import com.a16.yuejian.yuejian.model.SerachModel;

import java.util.List;

public class SerachActivity extends AppCompatActivity implements View.OnClickListener,View.OnKeyListener{
    private EditText serach;
    private TextView back;
    private RecyclerView recyclerview;
    private Context mContext;

    Listener<Serach> listener = new Listener<Serach>() {
        @Override
        public void onResponse(List<Serach> t) {
            if (t.size()==0){
                Toast.makeText(SerachActivity.this,"没有你想搜索的东西！", Toast.LENGTH_SHORT).show();
            }else {
                SerachAdapter serachAdapter = new SerachAdapter(SerachActivity.this);
                serachAdapter.setList(t);
                recyclerview.setAdapter(serachAdapter);
            }
        }

        @Override
        public void onFail() {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serach);
        initView();
        initEvent();
    }

    private void initEvent() {
        back.setOnClickListener(this);
        serach.setOnKeyListener(this);
    }

    private void initView() {
        serach = (EditText)findViewById(R.id.serach_et);
        back = (TextView)findViewById(R.id.serach_back);
        recyclerview = (RecyclerView)findViewById(R.id.rv_serach);
        recyclerview.setLayoutManager(new LinearLayoutManager(SerachActivity.this));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.serach_back:
                finish();
                break;
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
            ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(SerachActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            serach();
        }
        return false;
    }

    private void serach() {
        SerachModel serachModel = new SerachModel();
        serachModel.serach(serach.getText().toString(),listener);
    }
}
